package cn.kgc.commons.advice;

import cn.kgc.base.entity.SysLog;
import cn.kgc.base.mapper.SysLogMapper;
import cn.kgc.commons.annoation.DictLog;
import cn.kgc.commons.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/**
 * <p>记录用户的操作日志信息</p>
 *
 * @author 卢传琪
 */
@Aspect
@Component
@Slf4j
public class DictAdvice {

    @Pointcut("@annotation(cn.kgc.commons.annoation.DictLog)")
    public void autoLogPointCut(){}

    @Resource
    private SysLogMapper sysLogMapper;

    @Around("autoLogPointCut()")
    public Object autoLogAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();//开始时间
        Object result=joinPoint.proceed();//调用目标方法
        long endTime = System.currentTimeMillis();//结束时间
        long costTime = endTime - startTime;//耗时
        saveLog(joinPoint,costTime); //保存日志
        return result;
    }

    /**
     * 保存日志
     * @param joinPoint
     * @param costTime
     */
    private void saveLog(ProceedingJoinPoint joinPoint,long costTime){

        MethodSignature methodSignature=(MethodSignature) joinPoint.getSignature();
        Method method= methodSignature.getMethod(); //目标方法(使用了@DictLog注解)
        //获得目标方法上的注解信息
        DictLog dictLog= method.getAnnotation(DictLog.class);
        String logContent=dictLog.logContent();
        int logType=dictLog.logType().getLogType();
        String name=dictLog.moduleName().getName();
        int operateType=dictLog.operateType().getOperateType();

        //获得目标方法类名
        String className=joinPoint.getTarget().getClass().getName();
        String methodName=className+","+method.getName();

        //获得请求地址
        HttpServletRequest httpServletRequest= SpringContextUtils.getHttpServletRequest();
        String requestURI=httpServletRequest.getRequestURI();

        //todo 从请求头中获得用户的id和用户名
        Long userId=0L;
        String userName="admin";

        SysLog sysLog=SysLog.builder().costTime(costTime)
                .logContent(logContent)
                .logType(logType)
                .method(methodName)
                .moudulename(name)
                .operateType(operateType)
                .requestUrl(requestURI)
                .userId(userId)
                .userName(userName)
                .build();
        log.info("日志增强获得的日志信息:{}",sysLog);
        sysLogMapper.insert(sysLog);
    }
}
